import React, { Component } from 'react'
import { Modal, Button, Input, Icon ,notification  } from 'antd';
import { connect } from 'react-redux'
import { getData } from "../../actions/Tabs";
import { AddClassName } from '../../api/index' 
class Add extends Component {
  state = {
    loading: false,
    visible: false,
    name: '',
    remake: ''
  };
  showModal = () => {
    this.setState({
      visible: true,
    });
  };
  openNotificationWithIcon = type => {
    if(type === 'success'){
      notification[type]({
        message: '提示',
        description:'添加成功',
      });
    } else if(type ==='Warning'){
      notification[type]({
        message: '提示',
        description:'添加失败,请重试',
      });
    }else{
      notification[type]({
        message: '提示',
        description:'输入框不能为空',
      });
    }
  };
  handleOk = async () => {
    if (this.state.name && this.state.remake) {
      let res = await AddClassName(this.state)
      if(res.data.code){ //失败
        this.openNotificationWithIcon('error')
        this.setState({ loading: true });
      }else{
        this.setState({ loading: false, visible: false });
        this.props.AddData();
        this.openNotificationWithIcon('success')
      }
    } else {
      this.openNotificationWithIcon('warning')
    }
  };

  handleCancel = () => {
    this.setState({ visible: false });
  };

  render() {
    const { visible, loading } = this.state;
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>
          添加班级
        </Button>
        <Modal
          visible={visible}
          title="添加班级"
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              返回
            </Button>,
            <Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
              添加
            </Button>,
          ]}
        >
          <Input
            placeholder="班级名称"
            size="large"
            prefix={<Icon type="user" />}
            onChange={(e) => this.setState({ name: e.target.value })}
          />
          <br />
          <br />
          <Input
            placeholder="备注"
            size="large"
            prefix={<Icon type="pushpin" />}
            onChange={(e) => this.setState({ remake: e.target.value })}
          />
        </Modal>
      </div>
    );
  }
}
const mapDispatch2props = (dispatch) => {
  return {
    AddData() {
      const action = getData();
      dispatch(action)
    }
  }
}

export default connect(null, mapDispatch2props)(Add)